<?php
namespace Common\Lib\Chaboshi;

class CBS{

	protected static $userid = "90";
	protected static $keySecret = "c57e7d1d2cbf9703f5de2a0afd6e67c0";
	protected  static $cbsUrl = "http://api.chaboshi.cn/";

	private static $_instance;
	
	private function __construct($userid='', $keySecret=''){
		$this->userid =  $userid;
        $this->keySecret = $keySecret;
	}
	
	public function __clone(){
		trigger_error('Clone is not allow!',E_USER_ERROR);
	}
	
	public static function getInstance(){
		$userid = self::$userid;
		$keySecret = self::$keySecret;
		if($userid === null || empty($userid)){
            return null;
        }
        if($keySecret === null || empty($keySecret)){
            return null;
        }
		
		if(!(self::$_instance instanceof self)){
			self::$_instance = new CBS($userid,$keySecret);
		}
		return self::$_instance;
	}
	
	public function test(){
		echo '调用方法成功';
	}
	
	/**
	 * 判断该vin码是否支持查询
	 * @param vin 车架号(必填)
	 * @return {status : 状态码 ， message : 结果描述 }
	 */
	public function getCheckBrand($vin){
		$param = $this->param(null,$vin); 
		$url = self::$cbsUrl."report/check_brand?".$param;
		$sendGet = file_get_contents($url);
		return $sendGet;
	}
	
	/**
	 * 购买报告
	 * @param vin 车架号(必填)
	 * @param enginno 发动机号(非必填)
	 * @param licensePlate 车牌号(非必填)
	 * @param callbackurl 回调地址
	 * @return  成功：{"status":1,"orderId":"订单号,"message":"描述结果信息"}</br>
	 * 		            失败：{"Code":结果代码,"Message":"描述结果信息"}	
	 */
	public function getBuyReport($vin,$enginno,$licensePlate,$callbackurl){
		$param = $this->param(null,$vin,null,null,$callbackurl); 
		$url = self::$cbsUrl."report/buy_report";
		$sendPost = $this->sentPost($url,$param); 
		return $sendPost;
	}
	
	
	/**
	 * 获取报告状态
	 * @param orderid 订单ID(必填)
	 * @return  {"Code":结果代码,"Message":"描述结果信息"}
	 */
	public function getReportStatus($orderid){
		$param = $this->param($orderid); 
		$url = self::$cbsUrl."report/get_report_status?".$param;
		$sendGet = file_get_contents($url);
		return $sendGet;
	}
	
	/**
	 * 获取报告URL
	 * @param orderid 订单ID(必填)
	 * @return key → pcUrl：电脑端url、mobileUrl：手机端url
	 */
	public function getReportUrl($orderid){ 
		$param = $this->param($orderid); 
		$urlPC = self::$cbsUrl."report/show_report?" . $param;
		$urlMobile = self::$cbsUrl."report/show_reportMobile?" . $param;
		$result=array(); 
		array_push($result,$urlPC,$urlMobile); 
		return $result;
	}
	
	/**
	 * 获取新版报告URL
	 * @param orderid 订单ID(必填)
	 * @return key → pcUrl：电脑端url、mobileUrl：手机端url
	 */
	public function getNewReportUrl($orderid){ 
		$param = $this->param($orderid); 
		$urlPC = self::$cbsUrl."new_report/show_report?" . $param;
		$urlMobile = self::$cbsUrl."new_report/show_reportMobile?" . $param;
		$result=array(); 
		array_push($result,$urlPC,$urlMobile); 
		return $result;
	}
	
	
	/**
	 * 获取报告Json数据
	 * @param orderid 订单ID(必填)
	 * @return
	 */
	public function getReportJson($orderid){
		$param = $this->param($orderid);
		$url = self::$cbsUrl."report/get_report?".$param;
		$sendGet = file_get_contents($url);
		return $sendGet;
	}
	
	
	/**
	 * 获取新版报告Json数据
	 * @param orderid 订单ID(必填)
	 * @return
	 */
	public function getNewReportJson($orderid){
		$param = $this->param($orderid);
		$url = self::$cbsUrl."new_report/get_report?".$param;
		$sendGet = file_get_contents($url);
		return $sendGet;
	}
	
	/**
	 * 拼装参数  ascii码从小到大
	 * @param orderid 订单id
	 * @param vin 车架号
	 * @param enginno 发动机号
	 * @param licensePlate 车牌号
	 * @callbackurl 回调地址
	 * @return
	 */
	function param($orderid,$vin='',$enginno='',$licensePlate='',$callbackurl=''){
		
		$timestamp = $this->msectime(); 		
        $nonce = uniqid();		
        $content = '';
		$content .= 'timestamp' . '=' . $timestamp;
		$content .= '&userid='.$this->userid;
		$content .= '&nonce' . '=' . $nonce;

		if($enginno != null && !empty($enginno)){
            $content.= 'enginno' .  '=' . $enginno;
        }
		if($licensePlate != null && !empty($licensePlate)){
            $content.= '&licenseplate' . '=' . $licensePlate;
        }
		if($callbackurl != null && !empty($callbackurl)){
            $content.= '&callbackurl' . '=' . $callbackurl;
        }
		if($orderid != null && !empty($orderid)){
            $content .= '&orderid' . '=' . $orderid;
        }
        if($vin != null && !empty($vin)) {
           $content .='&vin' . '=' . $vin;
        }
        $signAture = null;
        try {
            $signAture = self::sign($content,$this->keySecret);
        } catch (\Exception $e) {
            var_dump($e->__toString());
        }
        $content.= '&signature' . '=' . $signAture;		
        return $content;
	} 
	
	
	/*
	*获取毫秒级时间戳
	*/
	function msectime() {
       list($tmp1, $tmp2) = explode(' ', microtime());
       return (float)sprintf('%.0f', (floatval($tmp1) + floatval($tmp2)) * 1000);
	}
	
	/**
	 * 通过参数获取签名
	 * @param paramsStr 参数串
	 * @param secretkey 商户私钥
	 * @return  sign 签名串
	 */
	function sign($paramsStr,$secretkey){
		if(empty($paramsStr)||$paramsStr==null||empty($secretkey)||$secretkey==null){
			return "";
		}
		$i=0;
		$str='';
		$paramsStr=explode("&",$paramsStr);
		asort($paramsStr);
		foreach($paramsStr as $key=>$value){
			if($i<count($paramsStr)-1){
				$str.=$value.'&';
			}else{
				$str.=$value;
			}
			$i ++;
		} 
		$str=urlencode($str);
		$sign=base64_encode(hash_hmac("sha1", $str, $secretkey, true));
		$sign=urlencode($sign);
		return $sign;
	}
	
	/*
	*发送post请求
	*/
	function sentPost($url, $param)
    {
        $aContext = array(
            'http' => array(
                'method' => 'POST',                
                'header' => 'Content-type: application/x-www-form-urlencoded',                
                'content' => $param
            )
        );
        
        $cxContext = stream_context_create($aContext);
        $d = @file_get_contents($url, false, $cxContext);
        return $d;
    }
}


